import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import fenceManageApi from "@/api/basic-info-manage/fence-management";

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/','/chooseSystem','/dataMonitoring','/statisticalData','/historyData','/deviceManage'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  const hasToken = whiteList.includes(to.path) ? '' : getToken();
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if(!determineRouter(to)){
        Message.warning('未配置访问页面权限')
        return
      }
      const hasGetUserInfo = store.getters.name
      const { data: onInfo } =
      await fenceManageApi.queryonInfoByCondition();
      store.dispatch('app/warrantyStatus', onInfo)

      if (hasGetUserInfo) {

        next()
      } else {
        try {
          await store.dispatch('user/getInfo')
          next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      let redirect = ''
      if (to.path && to.path !== '/404') {
        redirect = `?redirect=${to.path}`
      } else {
        redirect = ''
      }
      next(`/login${redirect}`)
      NProgress.done()
    }
  }
})
function determineRouter(to){
  console.log(whiteList.includes(to.path))
  let router = JSON.stringify(store.state.app.router);
  return router.includes(to.path) || whiteList.includes(to.path)
}
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
